package com.soundplus.app.shp04.Activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.sppmode.Common.AllParam;
import com.soundplus.app.shp04.R;
import com.soundplus.app.shp04.databinding.ActivityRestoreDefaultBinding;

public class RestoreDefaultActivity extends AppCompatActivity {

    private static final int MSGID_CLEAR_RESULT = 1;

    private static final int CLEAR_BIT_USER_INFO = 0;
    private static final int CLEAR_BIT_PAIR_DEV = 1;
    private static final int CLEAR_BIT_HEARING_RECORD = 2;
    private static final int CLEAR_BIT_DEVICE_CTRL = 3;

    private Context context;
    private ActivityRestoreDefaultBinding binding;
    private MyHandler myHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;
        binding = ActivityRestoreDefaultBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        myHandler = new MyHandler(context, getMainLooper());
        initView();
    }

    private void initView() {
        binding.btnClean.setOnClickListener(view -> restoreDefaultValue());
    }

    private class MyHandler extends Handler {
        Context context;
        Looper looper;

        public MyHandler(Context context, Looper looper) {
            super(looper);
            this.context = context;
            this.looper = looper;
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSGID_CLEAR_RESULT) {
                if (msg.arg1 == 0) {
                    Toast.makeText(context, R.string.clear_complete, Toast.LENGTH_SHORT).show();
                } else {
                    String failStr = "";

                    Toast.makeText(context, failStr, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private boolean isClearing = false;

    private void restoreDefaultValue() {
        if (!isClearing) {
            isClearing = true;
            new Thread(() -> {
                int clear = 0;
                try {


                    if (binding.cbCleanDevInfo.isChecked()) {
                        if (!AllParam.getPairedDevInfo().clear())
                            clear |= (1 << CLEAR_BIT_PAIR_DEV);


                    }



                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    isClearing = false;
                    myHandler.sendMessage(myHandler.obtainMessage(MSGID_CLEAR_RESULT, clear, 0));
                }
            }).start();
        }

    }
}
